import json
import pyaudio
import wave
import re
from AipSpeech import aip_speech_client


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


def record(record_time):
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 2
    RATE = 44100
    RECORD_SECONDS = record_time
    WAVE_OUTPUT_FILENAME = "record_output.wav"
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    print("* 开始录音")
    frames = []
    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        data = stream.read(CHUNK)
        frames.append(data)
    print("* 录音结束")
    stream.stop_stream()
    stream.close()
    p.terminate()
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

    client = aip_speech_client.get_baidu_client();
    result = client.asr(get_file_content("record_output.wav"), 'wav', 16000, {
        'dev_pid': '1536',
    })
    print("转换前数据："+str(result))
    temp = json.loads(re.sub('\'', '\"', str(result)))
    print("转换后数据："+str(temp))
    if(temp["err_no"] == 0 and temp["result"] is not None):
        return temp["result"]
    else:
        print("语音解析失败")
        return